﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrmApplication.Models;

namespace CrmApplication.Controllers
{
    public class SubpositionController : Controller
    {
        //
        // GET: /SubPosition/

        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// get all subpositions for selected domain(select by id)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSubposition()
        {
            string searchPos= Request.Params["query"];
            decimal positionId = 0;
            Decimal.TryParse(Request.Params["position_id"], out positionId);
            SubpositionContainer container = SubpositionModels.GetSubposArray(searchPos, positionId);
            return Json(container, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// add new subposition
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSubposition()
        {
            SubpositionModels subposition = new SubpositionModels();
            string messageBack =null;
            decimal positionId = 0;
            Decimal.TryParse(Request.Params["position"], out positionId);

            subposition.Name = Request.Params["subposition"];
            subposition.IdPosition = positionId;

            SubpositionModels checkSubpos = new SubpositionModels();
            checkSubpos=SubpositionModels.CheckSubposition(subposition);

            try
            {
                if (subposition.Name != "")
                {
                    if (checkSubpos==null)
                    {
						 SubpositionModels.AddSubPosition(subposition);
                    }
                    else
                    {
                        messageBack = "Subfunctia exista deja";
                    }
                }

				return Json(new { success = true, description = messageBack });
            }
			catch (Exception ex)
			{
				if (ex.Message.Contains("unique key constraint"))
				{
					messageBack = "Exista deja o inregistrare cu acelasi nume!";
				}
				return Json(new { success = true, description = messageBack });
			}
        }

    }
}
